﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;

namespace XMM.Objects
{
    public class SeriesSeason : Object
    {
        /// <summary>
        /// Season Database-Record ID.
        /// </summary>
        public int SeasonID { get; set; }

        /// <summary>
        /// Assigned Series Database-Record ID.
        /// </summary>
        public int SeriesID { get; set; }

        /// <summary>
        /// Season or Volume Number.
        /// </summary>
        public int Number { get; set; }

        /// <summary>
        /// Is this Season's Collection complete?
        /// </summary>
        public bool Complete { get; set; }

        /// <summary>
        /// If completed, date of completition.
        /// </summary>
        public DateTime DateComplete { get; set; }

        /// <summary>
        /// All existing Episodes for this season.
        /// </summary>
        public List<SeriesEpisode> Episodes { get; set; }

        public string BaseDirectory { get; set; }

        /// <summary>
        /// Initialize a new Season-Object.
        /// </summary>
        public SeriesSeason()
        {
            blankValues();
        }

        /// <summary>
        /// Initialize a new Season-Object and assign values from database-record.
        /// </summary>
        /// <param name="iSeasonID">(int) Target-Season Database-Record ID</param>
        public SeriesSeason(int iSeasonID)
        {
            Load(iSeasonID);
        }

        public override string ToString()
        {
            return "Staffel " + Number.ToString();
        }

        /// <summary>
        /// Reset all values.
        /// </summary>
        public void blankValues()
        {
            SeasonID = 0;
            SeriesID = 0;
            Number = 0;
            Complete = false;
            DateComplete = DateTime.MinValue;
            Episodes = new List<SeriesEpisode>();
            BaseDirectory = String.Empty;
        }

        public static bool Delete(int iSeasonID)
        {
            if (iSeasonID != 0)
            {
                Objects.SeriesSeason oSeason = new SeriesSeason(iSeasonID);
                Objects.Series oShow = new Series(oSeason.SeriesID);
                foreach (Objects.SeriesEpisode oEpisode in oSeason.Episodes)
                {
                    if (oEpisode.Delete() == false)
                    {
                        MessageBox.Show("\"" + oShow.Name + "\", Staffel " + oSeason.Number.ToString() + ", Episode " + oEpisode.EpisodeNo.ToString() + " wurde nicht gelöscht!", "Fehler beim Löschen", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return false;
                    }
                }

                try
                {
                    XMMDBDataContext dbConnection = new XMMDBDataContext();

                    t_series_seasons vSeason = (from season in dbConnection.t_series_seasons where season.ID == iSeasonID select season).Single();

                    if (vSeason != null && vSeason.ID > 0)
                    {
                        dbConnection.t_series_seasons.DeleteOnSubmit(vSeason);
                        dbConnection.SubmitChanges();

                        return true;
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show("Fehler beim Löschen der Staffel: " + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            return false;
        }

        public bool Delete()
        {
            return Objects.SeriesSeason.Delete(SeasonID);
        }

        /// <summary>
        /// Load values from a specific database-record.
        /// </summary>
        /// <param name="iSeasonID">(int) Target-Season Database-Record</param>
        /// <returns>[true] if record was loaded successfully.</returns>
        public bool Load(int iSeasonID)
        {
            blankValues();

            if (iSeasonID != 0)
            {
                try
                {
                    XMMDBDataContext dbConnection = new XMMDBDataContext();

                    var vSeason = (from season in dbConnection.t_series_seasons where season.ID == iSeasonID select season).Single();

                    if (vSeason != null && vSeason.ID != 0)
                    {
                        SeasonID = vSeason.ID;
                        SeriesID = vSeason.SeriesID;
                        Number = vSeason.Number;
                        if (vSeason.Complete == 1)
                            Complete = true;
                        else
                            Complete = false;
                        if (vSeason.DateComplete != null)
                            DateComplete = (DateTime)vSeason.DateComplete;

                        if (vSeason.BaseDirectory != null)
                            BaseDirectory = vSeason.BaseDirectory;
                        else
                            BaseDirectory = String.Empty;

                        Episodes = getSeasonEpisodes(SeasonID);

                        return true;
                    }
                    else
                    {
                        MessageBox.Show("Die gesuchte Staffel wurde nicht in der Datenbank gefunden!", "Unbekannte Staffel", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show("Fehler beim Laden der Staffel '" + iSeasonID.ToString() + "': " + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                MessageBox.Show("Bitte wählen Sie eine gültige Staffel aus!", "Ungültige Staffel", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }

            return false;
        }

        /// <summary>
        /// Save this Season as new database-record.
        /// </summary>
        /// <returns>[true] if Season was saved successfully.</returns>
        public bool SaveNew()
        {
            if (SeriesID != 0 && Number != 0)
            {
                try
                {
                    XMMDBDataContext dbConnection = new XMMDBDataContext();

                    t_series_seasons vSeason = new t_series_seasons();
                    vSeason.SeriesID = SeriesID;
                    vSeason.Number = Number;

                    if (Complete)
                    {
                        vSeason.Complete = 1;
                        vSeason.DateComplete = DateComplete;
                    }
                    else
                    {
                        vSeason.Complete = 0;
                        vSeason.DateComplete = null;
                    }

                    vSeason.BaseDirectory = BaseDirectory;

                    dbConnection.t_series_seasons.InsertOnSubmit(vSeason);
                    dbConnection.SubmitChanges();

                    return true;                        
                }
                catch (SqlException ex)
                {
                    MessageBox.Show("Fehler beim Speichern der neuen Staffel: " + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else if (SeriesID == 0)
                MessageBox.Show("Bitte wählen Sie zuerst eine Serie aus!", "Keine Serie ausgewählt", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            else if (Number == 0)
                MessageBox.Show("Bitte geben Sie die Nummer der Staffel/des Volumes ein!", "Keine Staffel-Nummer", MessageBoxButton.OK, MessageBoxImage.Exclamation);

            return false;
        }

        /// <summary>
        /// Save changes to an existing Season-Database-Record.
        /// </summary>
        /// <returns></returns>
        public bool SaveChanges()
        {
            if (SeriesID != 0 && Number != 0 && SeasonID != 0)
            {
                try
                {
                    XMMDBDataContext dbConnection = new XMMDBDataContext();

                    t_series_seasons vSeason = (from season in dbConnection.t_series_seasons where season.ID == SeasonID select season).Single();

                    if (vSeason != null && vSeason.ID != 0)
                    {
                        vSeason.SeriesID = SeriesID;
                        vSeason.Number = Number;

                        if (Complete)
                        {
                            vSeason.Complete = 1;
                            vSeason.DateComplete = DateComplete;
                        }
                        else
                        {
                            vSeason.Complete = 0;
                            vSeason.DateComplete = null;
                        }

                        vSeason.BaseDirectory = BaseDirectory;

                        dbConnection.SubmitChanges();
                        return true;
                    }
                    else
                    {
                        MessageBox.Show("Die gewählte Staffel ist in der Datenbank nicht verfügbar! Bitte erstellen Sie eine neue Staffel!", "Staffel nicht gefunden", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show("Fehler beim Speichern der Änderungen an Staffel '" + SeasonID.ToString() + "' :" + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else if (SeriesID == 0)
                MessageBox.Show("Bitte wählen Sie zuerst eine Serie aus!", "Keine Serie ausgewählt", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            else if (Number == 0)
                MessageBox.Show("Bitte geben Sie die Nummer der Staffel/des Volumes ein!", "Keine Staffel-Nummer", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            else if (SeasonID == 0)
                MessageBox.Show("Die gewählte Staffel ist in der Datenbank nicht verfügbar! Bitte erstellen Sie eine neue Staffel!", "Staffel nicht gefunden", MessageBoxButton.OK, MessageBoxImage.Exclamation);


            return false;
        }

        /// <summary>
        /// Get all Episodes for a given Season-Database-ID.
        /// </summary>
        /// <param name="iTargetSeasonID">(int) Target-Season ID</param>
        /// <returns>[List(SeriesEpisode)] List of Episodes assignes to the selected SeasonID.</returns>
        public static List<SeriesEpisode> getSeasonEpisodes(int iTargetSeasonID)
        {
            List<SeriesEpisode> lEpisodes = new List<SeriesEpisode>();

            try
            {
                if (iTargetSeasonID != 0)
                {
                    XMMDBDataContext dbConnection = new XMMDBDataContext();

                    var vEpisodes = from episodes in dbConnection.t_series_episodes where episodes.SeasonID == iTargetSeasonID orderby episodes.EpisodeNo ascending select episodes.ID;

                    if (vEpisodes != null && vEpisodes.Count() > 0)
                    {
                        foreach (int iEpisodeID in vEpisodes)
                        {
                            SeriesEpisode oEpisode = new SeriesEpisode(iEpisodeID);
                            if (oEpisode != null && oEpisode.EpisodeID != 0)
                                lEpisodes.Add(oEpisode);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Die angegebene Staffel konnte nicht in der Datenbank gefunden werden!", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Fehler beim Abrufen der Episoden aus \"[SERIE]\", Staffel \"[SEASON]\": " + ex.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            return lEpisodes;
        }

    }
}
